<?php
class Groups extends Controller{
	function Groups(){
		parent::Controller();
	}
	
	function index(){
		redirect('/groups/show/');
	}
	
	function show(){
		$this->load->model('Groupsdb');
		$data['theGroup'] = '';
		if($data['allGroups'] = $this->Groupsdb->getAllGroups()){
			for($i=0;$i<sizeOf($data['allGroups']['id']);$i++){
				$data['groupname'] [$i] = $data['allGroups']['groupname'][$i];
				$data['theGroup'] = $data['theGroup'].$this->_formatListGroup($data['groupname'] [$i]);
			}
		}
		$data['pageTitle'] = "Groups";
		$data['page'] = 'allgroup';
		$allGroup = $this->Groupsdb->getAllGroups(0,99999999);
		$data['num_messages'] = sizeOf($allGroup['groupname']);
		$this->load->view('groups',$data);
	}
	function _formatListGroup($groupname){
		$this->load->model('Groupsdb');
		$group = $this->Groupsdb->getGroup($groupname);
		if($group['avatar']==''){
			$group['avatar'] = 'default_group_avatar.png';
		}
		return "
		<li>
			<a href='".base_url()."groups/info/".$groupname."'>
				<img src='".base_url()."sknimg/i-see-attr/avatarThumb/".$group['avatar']."' width='50' height='50' class='avatarecho' alt='avatar'></img>
			</a>
			<div class='tweetTxt'> 
				<a style='text-decoration:none' href='".base_url()."groups/info/".$groupname."'>
					".$group['title']."
				</a>
				<div class='date'>".$group['num_followers']." pengikut</div>
			</div>
			<div class='clear'></div>
		</li>";
	}
	function create(){
		$this->load->model('Groupsdb');
		$allGroups = $this->Groupsdb->getAllGroups();
		$data['groupname'] = '';
		$data['namagroup'] = '';
		$data['deskripsi'] = '';
		$data['isError'] = FALSE;
		$data['errorMsg'] = '';
		$data['isSuccess'] = FALSE;
		if($this->input->post('creategroup')){
			$data['groupname'] = $this->input->post('groupname');
			$data['namagroup'] = $this->input->post('namagroup');
			$data['deskripsi'] = $this->input->post('deskripsi');
			if(empty($data['groupname'])){
				$data['isError'] = TRUE;
				$data['errorMsg'] = 'Harap isi Groupname';
			}elseif(empty($data['namagroup'])){
				$data['isError'] = TRUE;
				$data['errorMsg'] = 'Harap isi Nama Group';
			}elseif(strlen($data['groupname'])<3 || strlen($data['groupname'])>30){
				$data['isError'] = TRUE;
				$data['errorMsg'] = 'Panjang karakter untuk Groupname harus antara 3 sampai 30';
			}elseif(preg_match('/[^a-z0-9-_]/i', $data['groupname'])){
				$data['isError'] = TRUE;
				$data['errorMsg'] = 'Groupname hanya boleh terdiri dari karakter a-z,A-Z,0-9';
			}elseif($allGroups){
				if(in_array($data['groupname'],$allGroups['groupname'])){
					$data['isError'] = TRUE;
					$data['errorMsg'] = 'Groupname sudah diambil sebelumnya';
				}else{
					if($this->Groupsdb->createGroup($data['groupname'],$data['namagroup'],$data['deskripsi'],$this->session->userdata('userId'))){
						$data['isSuccess'] = TRUE;
					}
				}
			}else{
				if($this->Groupsdb->createGroup($data['groupname'],$data['namagroup'],$data['deskripsi'],$this->session->userdata('userId'))){
					$data['isSuccess'] = TRUE;
				}
			}
				
		}
		$data['pageTitle'] = "Membuat Group";
		$this->load->view('groups',$data);
	}
	
	function info($groupname=NULL){
		$this->load->model('Groupsdb');
		$data['isGroupAdmin'] = FALSE;
		$data['needLeave'] = FALSE;
		if($data['group'] = $this->Groupsdb->getGroup($groupname)){
			$data['gid']  = $data['group']['id'];
			$data['groupname']  = $data['group']['groupname'];
			$data['title'] = $data['group']['title'];
			$data['avatar']  = $data['group']['avatar'];
			if($data['avatar'] ==''){
				$data['avatar']  = 'default_group_avatar.png';
			}
			$data['about_me']  = $data['group']['about_me'];
			$data['num_followers']  = $data['group']['num_followers'];
			if($this->session->userdata('isLogin')){
				$data['isMyGroup'] = $this->Groupsdb->isMyGroup($this->session->userdata('userId'),$data['gid']);
				$data['isGroupAdmin'] = $this->Groupsdb->isGroupAdmin($this->session->userdata('userId'),$data['gid']);
			}
			if($this->input->post('join')){
				if($data['joinSuccess'] = $this->Groupsdb->joinGroup($this->session->userdata('userId'),$data['gid'])){
					$data['isMyGroup'] = TRUE;
					$data['num_followers'] = $data['num_followers']+1;
				}
					

			}elseif($this->input->post('leave')){
				if($data['isGroupAdmin']){
					$data['needLeave'] = TRUE;
				}else{
					if($data['leaveSuccess'] = $this->Groupsdb->leaveGroup($this->session->userdata('userId'),$data['gid'])){
						$data['isMyGroup'] = FALSE;
						$data['num_followers'] = $data['num_followers']-1;
					}
				}
			}elseif($this->input->post('noLeave')){
				//silence is golden
			}elseif($this->input->post('leaveDelete')){
				if($data['leaveSuccess'] = $this->Groupsdb->adminLeaveGroup($data['gid'])){
					$data['isMyGroup'] = FALSE;
					redirect('/groups/show/');
				}
			}
		}else{
			redirect('/groups/show/');
		}
		$data['pageTitle'] = "Group ".$data['title'];
		$this->load->view('groupProfile',$data);
	}
	
	function members($groupname=NULL){
		$this->load->model('Groupsdb');
		$this->load->model('UsersDetail');
		$this->load->model('UserMahasiswa');
		$this->load->model('User');
		if($data['group'] = $this->Groupsdb->getGroup($groupname)){
			$data['gid']  = $data['group']['id'];
			$data['groupname']  = $data['group']['groupname'];
			$data['title'] = $data['group']['title'];
			$data['avatar']  = $data['group']['avatar'];
			if($data['avatar'] ==''){
				$data['avatar']  = 'default_group_avatar.png';
			}
			$data['about_me']  = $data['group']['about_me'];
			$data['num_followers']  = $data['group']['num_followers'];
			if($data['membersGroup'] = $this->Groupsdb->getMembersGroup($data['gid'])){
				for($i=0;$i<sizeOf($data['membersGroup']['id']);$i++){
					$data['user_id'][$i] =  $data['membersGroup']['id'][$i];
					$data['username'][$i] = $this->User->getUsername($data['user_id'][$i]);
					$data['nama'][$i] = json_decode($this->UserMahasiswa->getNama($data['user_id'][$i]))->nama;
					$data['detail'][$i] = json_decode($this->UsersDetail->getDetail($data['user_id'][$i]));
					$data['useravatar'] [$i] = $data['detail'][$i]->avatar;
					if($data['useravatar'] [$i]==''){
						$data['useravatar'] [$i] = 'default_avatar.jpg';
					}
					$data['itIsGroupAdmin'][$i]= $this->Groupsdb->isGroupAdmin($data['user_id'][$i],$data['gid']);
				}
			}
			if($this->session->userdata('isLogin')){
				$data['isMyGroup'] = $this->Groupsdb->isMyGroup($this->session->userdata('userId'),$data['gid']);
				$data['isGroupAdmin'] = $this->Groupsdb->isGroupAdmin($this->session->userdata('userId'),$data['gid']);
			}
		}else{
			redirect('/groups/show/');
		}
		$data['pageTitle'] = "Anggota Group ".$data['title'];
		$this->load->view('groupProfile',$data);
	}
	
	function admins($groupname=NULL){
		$this->load->model('Groupsdb');
		$data ['noError'] = TRUE;
		if(!$this->session->userdata('isLogin')){
			redirect('/home/');
		}else{
			if($data['group'] = $this->Groupsdb->getGroup($groupname)){
				$data['gid']  = $data['group']['id'];
				$data['groupname']  = $data['group']['groupname'];
				$data['title'] = $data['group']['title'];
				$data['avatar']  = $data['group']['avatar'];
				if($data['avatar'] ==''){
					$data['avatar']  = 'default_group_avatar.png';
				}
				$data['about_me']  = $data['group']['about_me'];
				$data['num_followers']  = $data['group']['num_followers'];
				if(!$data['isGroupAdmin'] = $this->Groupsdb->isGroupAdmin($this->session->userdata('userId'),$data['gid'])){
					redirect("/groups/info/$groupname");
				}else{
					if($this->input->post('update')){
						if($this->Groupsdb->updateProfile($data['gid'] ,
															$this->input->post('namagroup'),
															$this->input->post('about_me'))){
							$data['title'] = $this->input->post('namagroup');
							$data['about_me'] = $this->input->post('about_me');
						}
						srand ((double) microtime( )*1000000);
						$fname = rand( );
						$config['upload_path'] = './sknimg/i-see-attr/avatar';
						$config['allowed_types'] = 'jpg|png';
						$config['max_size'] = '0';
						$config['file_name'] = md5($fname);
						$config['max_width'] = '0';
						$config['max_height'] = '0';
						$this->load->library('upload', $config);
						$data ['noError'] = $this->upload->do_upload('groupavatar');
						$data ['errorMsg'] = $this->upload->display_errors();
						if($this->upload->display_errors()=='<p>You did not select a file to upload.</p>'){
							$data ['noError'] = TRUE;
						}else{
							if($data ['noError']){
								$uploadData = $this->upload->data();
								$oldAvatar = $data['avatar'];
								$this->load->helper('file');
								if($uploadData['image_width']<200||$uploadData['image_height']<200){
									delete_file(realpath('./sknimg/i-see-attr/avatar'),md5($fname).$uploadData['file_ext']);
									$data ['noError'] = FALSE;
									$data ['errorMsg'] = "Ukuran Gambar Minimal 200px X 200px";
								}else{
									if($oldAvatar!='default_group_avatar.png'){
										delete_file(realpath('./sknimg/i-see-attr/avatar'),$oldAvatar);
										delete_file(realpath('./sknimg/i-see-attr/avatarThumb'),$oldAvatar);
									}
									$config['image_library'] = 'gd2';
									$config['source_image'] = realpath("./sknimg/i-see-attr/avatar/".md5($fname).$uploadData['file_ext']."");
									$config['create_thumb'] = FALSE;
									$config['maintain_ratio'] = TRUE;
									$config['width'] = 50;
									$config['new_image'] = './sknimg/i-see-attr/avatarThumb/'.md5($fname).$uploadData['file_ext'];
									$this->load->library('image_lib', $config);
									$data ['noError'] = $this->image_lib->resize();
									$data ['errorMsg'] = $this->image_lib->display_errors();
									if($data ['noError']){
										$this->Groupsdb->updateAvatar($data['gid'],md5($fname).$uploadData['file_ext']);
										$data['avatar'] = md5($fname).$uploadData['file_ext'];
									}else{
										delete_file(realpath('./sknimg/i-see-attr/avatar'),md5($fname).$uploadData['file_ext']);
									}									
								}
							}
						}
					}elseif($this->input->post('delete')){
						if($data['leaveSuccess'] = $this->Groupsdb->adminLeaveGroup($data['gid'])){
							redirect('/groups/show/');
						}
					}
				}
			}else{
				redirect('/groups/show/');
			}
		}
		$data['pageTitle'] = "Pengaturan Group ".$data['title'];
		$this->load->view('groupProfile',$data);
	}
	
	function echos($groupname=NULL){
		$this->load->model('Groupsdb');
		$this->load->model('Posts');
		$data['isGroupAdmin'] = FALSE;
		if($data['group'] = $this->Groupsdb->getGroup($groupname)){
			$data['gid']  = $data['group']['id'];
			$data['groupname']  = $data['group']['groupname'];
			$data['title'] = $data['group']['title'];
			$data['avatar']  = $data['group']['avatar'];
			if($data['avatar'] ==''){
				$data['avatar']  = 'default_group_avatar.png';
			}
			$data['about_me']  = $data['group']['about_me'];
			$data['num_followers']  = $data['group']['num_followers'];
			if($this->session->userdata('isLogin')){
				$data['isMyGroup'] = $this->Groupsdb->isMyGroup($this->session->userdata('userId'),$data['gid']);
				$data['isGroupAdmin'] = $this->Groupsdb->isGroupAdmin($this->session->userdata('userId'),$data['gid']);
			}
			
			
			$data['myEcho'] = $this->Posts->getPostGroup($data['gid'],0,10);
			if($myEcho = $data['myEcho']){
				$myEchoMsg ="";
				for($i=0;$i<sizeOf($myEcho['message']);$i++){
					$myEchoMsg = $myEchoMsg.$this->_formatEcho($myEcho['user_id'][$i],$myEcho['message'][$i],$myEcho['date'][$i],$myEcho['comments'][$i],$myEcho['post_id'][$i]);	
				}
				$data['myEchoMsg'] = $myEchoMsg;
			}else{
				$data['whatsWrong'] = 'Belum ada member yang Memberikan Echo kepada '.$data['title'].'';
			}
			$allposts = $this->Posts->getPostGroup($data['gid'],0,9999999999);
			$data['num_messages'] = sizeOf($allposts['message']);
			
			
		}else{
			redirect('/groups/show/');
		}
		$data['page'] = 'group';
		$data['pageTitle'] = "Echo Group ".$data['title'];
		$this->load->view('groupProfile',$data);
	}
	function _formatEcho($user_id,$message,$date,$commentNum=NULL,$post_id=NULL){
		
		$this->load->model('UsersDetail');
		$this->load->model('UserMahasiswa');
		$this->load->model('User');
		$this->load->model('Posts');
		$this->load->model('Attachment');
		$thisPost = $this->Posts->getPost($post_id);
		
		
		$attachedHTML='<ul id="listAttach">';
		if($thisPost['attached']==1){
			$postAttach = $this->Attachment->getAttachment($post_id);
			for($i=0;$i<sizeOf($postAttach['type']);$i++){
				if($postAttach['type'][$i]=='image'){
					$attachedHTML = $attachedHTML.'<li>
					<a href="'.base_url().'sknimg/i-see-attr/imageAttachment/'.$postAttach['data'][$i].'" class="lightbox-enabled" onclick="$(this).lightbox({start:true,events:false}); return false;" title="'.$postAttach['data'][$i].'">
						<img class="avatarecho" style="float:right;" src="'.base_url().'sknimg/i-see-attr/imageAttachmentThumb/'.$postAttach['data'][$i].'" width="50px" height="50px"  /></a>
					<br><strong style="font-size:11px;font-style:italic;">
					<img src="'.base_url().'sknimg/img/download.png" width="15" height="15"></img>
					<a href="'.base_url().'engine/download/item/'.$postAttach['data'][$i].'/image">
					Image Attachment: '.$postAttach['data'][$i].'</a></strong>
					<div class="tweetTxt">
					';
					$attachedHTML = $attachedHTML.'</div> <div class="clear"></div> </li>';
				}elseif($postAttach['type'][$i]=='file'){
					$attachedHTML = $attachedHTML.'<li>
					<a href="javascript:;"><img class="avatarecho" style="float:right;border:0" src="'.base_url().'sknimg/img/'.'file.png'.'" width="40px" height="45px"  /></a>
					<br><strong style="font-size:11px;font-style:italic;">
					<img src="'.base_url().'sknimg/img/download.png" width="15" height="15"></img>
					<a href="'.base_url().'engine/download/item/'.$postAttach['data'][$i].'/file">
					File Attachment: '.$postAttach['data'][$i].'</a></strong>
					<div class="tweetTxt">
					';
					$attachedHTML = $attachedHTML.'</div> <div class="clear"></div> </li>';
				}
			}
		}
		$attachedHTML=$attachedHTML."</ul>";
		
		$detail = json_decode($this->UsersDetail->getDetail($user_id));
		$avatar = $detail->avatar;
		$username = $this->User->getUsername($user_id);
		$nama = json_decode($this->UserMahasiswa->getNama($user_id))->nama;
		$href = '';
		if($commentNum>5){
			$href = 'href="'.base_url().'post/view/'.$post_id.'"';
		}else{
			$href = 'href="javascript:;" onCLick="getComment('.$post_id.');"';
		}
		//formatting
		$message = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" rel=\"nofollow\">\\2</a>", $message);
		$message = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" rel=\"nofollow\">\